package com.csust.automaticteach.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DateUnit;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.csust.automaticteach.exception.ErrorCode;
import com.csust.automaticteach.exception.ThrowUtils;
import com.csust.automaticteach.model.dto.chatsession.ChatSessionQueryRequest;
import com.csust.automaticteach.model.dto.chatsession.updateChatsessionRequest;
import com.csust.automaticteach.model.entity.Chatsession;
import com.csust.automaticteach.model.vo.chatsession.ChatSessionVO;
import com.csust.automaticteach.service.ChatsessionService;
import com.csust.automaticteach.mapper.ChatsessionMapper;
import com.csust.automaticteach.utils.MessageSerializer;
import org.springframework.ai.chat.messages.Message;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

import static com.csust.automaticteach.constant.OrderConstant.ASC;

/**
* @author 钰玟
* @description 针对表【t_chatsession(会话表)】的数据库操作Service实现
* @createDate 2025-07-09 21:01:18
*/
@Service
public class ChatsessionServiceImpl extends ServiceImpl<ChatsessionMapper, Chatsession>
    implements ChatsessionService{
    @Override
    public QueryWrapper<Chatsession> getChatSessionQueryWrapper(ChatSessionQueryRequest chatSessionQueryRequest) {
        Long userId = chatSessionQueryRequest.getUserId();
        String sortField = chatSessionQueryRequest.getSortField();
        String sortOrder = chatSessionQueryRequest.getSortOrder();
        QueryWrapper<Chatsession> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq(ObjUtil.isNotNull( userId), "userId", userId);
        queryWrapper.orderBy(ObjUtil.isNotEmpty(sortField),
                sortOrder.equals(ASC), sortField);
        return queryWrapper;
    }
    @Override
    public ChatSessionVO getChatSessionVO(Chatsession chatsession) {
        //验证会话是否存在
        ThrowUtils.throwIf(chatsession == null, ErrorCode.NOT_FOUND_ERROR,"未找到会话");
        String message = chatsession.getMessage();
        //反序列化消息列表
        List<Message> messageList = MessageSerializer.deserialize(message);
        //创建chatSessionVO
        ChatSessionVO chatSessionVO = new ChatSessionVO();
        //拷贝属性
        BeanUtil.copyProperties(chatsession,chatSessionVO);
        //额外设置的属性
        chatSessionVO.setMessages(messageList);
        //计算间隔时间   当前时间 now -  updateTime
        Date updateTime = chatsession.getUpdateTime();
        Date now = new Date();
        // 计算时间差（天）
        long intervalTime = DateUtil.between(updateTime, now, DateUnit.DAY);
        chatSessionVO.setIntervalTime(intervalTime);
        return chatSessionVO;
    }
    @Override
    public List<ChatSessionVO> getChatSessionVOList(List<Chatsession> records) {
        return records.stream().map(this::getChatSessionVO).collect(Collectors.toList());
    }

    @Override
    public Boolean updateChatsession(updateChatsessionRequest updateChatsessionRequest) {
        //1.获取消息列表
        List<Message> messages = updateChatsessionRequest.getMessages();
        //除了消息列表，和更改时间，其他属性进行拷贝
        Chatsession chatsession = new Chatsession();
        //1.1判断消息列表是否为空，即判断是否修改消息列表
        if(!(messages == null)){
//            //1.1.1拿到消息Id
//            Long id = updateChatsessionRequest.getId();
//            //1.1.2 查询消息
//            Chatsession byId = this.getById(id);
//            String byIdMessage = byId.getMessage();
//            //1.1.3反序列化
//            List<Message> deserialize = MessageSerializer.deserialize(byIdMessage);
//            deserialize.addAll();
            String message = MessageSerializer.serialize(updateChatsessionRequest.getMessages());
            chatsession.setMessage(message);
        }
        BeanUtil.copyProperties(updateChatsessionRequest,chatsession);
        chatsession.setUpdateTime(new Date());
        return this.saveOrUpdate(chatsession);
    }


}




